﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HairUnitScaler : MonoBehaviour
{
    public Vector3 origin;
    public Vector3 max;
    public Vector3 min;
    public LabelSlider thicknessSlider;
    public LabelSlider widthSlider;
    public LabelSlider lengthSlider;
    public List<HairUnit> unitsSelected;
    public HairUnitEmitter hue;
    public ManualGizmos manual;
    public void Init()
    {
        hue = GetComponentInParent<HairUnitEmitter>();
        unitsSelected = new List<HairUnit>(transform.GetComponentInParent<HairUnitEmitter>().hairUnits);
        thicknessSlider.Init(origin.z, min.z, max.z, OnThicknessChanged);
        widthSlider.Init(origin.x, min.x, max.x, OnWidthChanged);
        lengthSlider.Init(origin.y, min.y, max.y, OnLengthChanged);
    }
    void ResetRotation(HairUnit unit)
    {
        var bones = unit.baker.bones;
        for (int i = 0; i < bones.Length; i++)
        {
            var sectionI = bones[i];
            var absolutePos = sectionI.position;
            var c = sectionI.GetChild(0);
            var absolutePosC = c.position;
            var absoluteRotC = c.rotation;
            var iDir = (absolutePosC - absolutePos).normalized;
            var iRot = Quaternion.FromToRotation(sectionI.up, iDir);
            sectionI.rotation = iRot * sectionI.rotation;
            if (i > 0)
            {
                var y = i == 1 ? -90 : 0;
                sectionI.localEulerAngles = sectionI.localEulerAngles.SetY(y);
            }
            c.position = absolutePosC;
            c.rotation = absoluteRotC;
        }
    }
    public void ApplyUnitValue(HairUnit unit)
    {
        //section pos
        //...
        //...

        unit.shape.Revert();
        unit.shape.Apply();
        unit.shape.SolveAll();
        ResetRotation(unit);        
        unit.UpdateColliderAndSectionTrans();
    }
    public void OnLengthChanged(HairUnit unit,float v)
    {
        if (hue.sdMgr.ignoreValueChanges) return;
        unit.baker.ScaleBone(v);
        unit.shape.Revert();
        unit.shape.Apply();
        unit.shape.SolveAll();
        ResetRotation(unit);        
        unit.UpdateColliderAndSectionTrans();
    }
    public void OnThicknessChanged(float v)
    {
        if (hue.sdMgr.ignoreValueChanges) return;
        manual.AllSectionThicknessChanged(v);
    }
    public void OnWidthChanged(float v)
    {
        if (hue.sdMgr.ignoreValueChanges) return;
        manual.AllSectionWidthChanged(v);
    }
    public void OnLengthChanged(float v)
    {
        if (hue.sdMgr.ignoreValueChanges) return;
        foreach (var unit in unitsSelected)
        {
            OnLengthChanged(unit,v);
            if (unit.mirror != null && SliderMgr.mirrorControl)
            {
                OnLengthChanged(unit.mirror,v);
            }
        }
    }
}
